package nwsimplex.core;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import nwsimplex.graph.SpanningTree;
import nwsimplex.io.read.controller.FileFormatException;
import nwsimplex.io.read.controller.ParserGraphDataImpl;
import nwsimplex.io.read.model.RawGraphData;

/**
 * The main class that runs the program. In general, does three things: <ol>
 * <li>Parses the given file</li> <li>Runs the algorithm</li> <li>Stores the
 * result</li> </ol> Carries about nothing else.
 *
 * @author Kseniya
 */
public class NWSimplex {

    public static void main(String[] args) {

        String inputFile = null;
        String outputFile = null;

        if (args != null && args.length == 2) {
            inputFile = args[0];
            outputFile = args[1];
        }
        // if no valid input file provided, prompt the user to input one manually
        if (inputFile == null || !isValidInputFile(inputFile)) {
            inputFile = promptUserInput("Enter path to file containing graph data:");
        }
        if (outputFile == null || !isValidFile(outputFile)) {
            outputFile = promptUserOutput("Enter path where to write the calculation result:");
        }
        try {
            RawGraphData parsedData = new ParserGraphDataImpl().parse(Paths.get(inputFile));
            SpanningTreeFactoryAbstract factory = new SpanningTreeFactory(parsedData);
            SpanningTree spanningTree = factory.createSpanningTree();
            AbstractMCFSolver solver = new MCFSolverImpl(spanningTree);
            solver.run();
            // TODO write the calculation result here
        } catch (IOException | FileFormatException ex) {
            System.out.println("Parsing ended unexpectedly. Reason: " + ex.getMessage());
        }
    }

    private static String promptUserInput(String promptMsg) {
        System.out.println(promptMsg);
        Scanner scanner = new Scanner(System.in);
        String userInput = scanner.nextLine();
        while (!isValidInputFile(userInput)) {
            System.out.println("Invalid file path. Please try again.");
            userInput = scanner.nextLine();
        }
        return userInput;
    }

    private static String promptUserOutput(String promptMsg) {
        System.out.println(promptMsg);
        Scanner scanner = new Scanner(System.in);
        String userInput = scanner.nextLine();
        while (!isValidFile(userInput)) {
            System.out.println("Invalid file path. Please try again.");
            userInput = scanner.nextLine();
        }
        return userInput;
    }

    private static boolean isValidFile(String fileName) {
        try {
            return !Files.isDirectory(Paths.get(fileName));
        } catch (Exception e) {
            return false;
        }
    }

    private static boolean isValidInputFile(String fileName) {
        return isValidFile(fileName) && Files.isReadable(Paths.get(fileName));
    }
}
